package top.oneit.jdownload.service;

import javafx.application.Platform;
import top.oneit.jdownload.constants.JConstants;
import top.oneit.jdownload.data.dao.DownloadFileDao;
import top.oneit.jdownload.data.dao.DownloadSaveStatusDao;
import top.oneit.jdownload.data.dao.DownloadingTablePoDao;
import top.oneit.jdownload.data.entity.DownloadFile;
import top.oneit.jdownload.data.entity.DownloadingTablePo;
import top.oneit.jdownload.stages.HomeStage;
import top.oneit.jdownload.utils.AssetsUtils;

import java.io.File;
import java.util.Timer;

/**
 * @author lingkang
 * Created by 2021/12/27
 */
public class DownloadTaskService extends BaseService{
    public static boolean checkComplete(DownloadingTablePo tablePo, Timer timer){
        int downloadCompleteNumber = DownloadSaveStatusDao.getDownloadCompleteNumber(tablePo);
        if (downloadCompleteNumber==tablePo.getDownloadFile().getThreadNumber()){
            DownloadFile downloadFile = tablePo.getDownloadFile();
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    timer.cancel();
                    // 下载完成
                    File rename = new File(downloadFile.getSavePath() + File.separator + downloadFile.getSaveName() + ".j");
                    rename.renameTo(new File(downloadFile.getSavePath() + File.separator + downloadFile.getSaveName()));

                    downloadFile.setStatus(JConstants.FILE_STATUS_FINISH);
                    DownloadFileDao.update(downloadFile);
                    DownloadSaveStatusDao.deleteByDownloadingTablePo(tablePo);
                    tablePo.setStatus(JConstants.FILE_STATUS_FINISH);
                    DownloadingTablePoDao.update(tablePo);

                    AssetsUtils.playerDownloadCompleteMusic();
                    // 刷新表格
                    getStage(HomeStage.class).refreshTable();
                }
            });
            return true;
        }
        return false;
    }
}
